package com.wyt.common.sqljdbc;

import org.apache.commons.lang3.StringUtils;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName SqlUtils
 * @Description: sql格式化以及结果统一处理工具类
 * @Author wangyongtao
 * @Date 2023/6/17 19:38
 * @Version 1.0
 **/
public class SqlResultUtils {


    /**
     * 格式化sql，将分号连接的sql拆开放入到list集合中
     */
    public static List<String> formatsqllist(String sql) {
        List<String> result = new ArrayList<>();
        if (StringUtils.isBlank(sql)) return result;
        for (String str : sql.split(";")) result.add(str.trim());
        result = result.stream().filter(s -> StringUtils.isNotBlank(s)).collect(Collectors.toList());
        return result;
    }

    /**
     * 获取sql查询结果的表头
     */
    public static List<String> getTitles(ResultSet resultSet) throws Exception {
        List<String> titles = new ArrayList<>();
        int colNum = resultSet.getMetaData().getColumnCount();
        for (int col = 0; col < colNum; col++) {
            String columnName = resultSet.getMetaData().getColumnName(col + 1);
            titles.add(columnName);
        }
        return titles;
    }

    /**
     * 获取sql查询出的结果数据集合，返回格式为[ 字段名：字段值 ]
     */
    public static List<Map<String, Object>> getData(ResultSet resultset) throws Exception {
        List<Map<String, Object>> data = new ArrayList<>();
        int colNum = resultset.getMetaData().getColumnCount();
        while (resultset.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int col = 0; col < colNum; col++) {
                String columnName = resultset.getMetaData().getColumnName(col + 1);
                Object columnvalue = resultset.getObject(columnName);
                map.put(columnName, columnvalue);
            }
            data.add(map);
        }
        return data;
    }

    /**
     * 专用（获取表列表）
     */


}
